//
//  ViewController.m
//  hunba
//
//  Created by 孙智慧 on 15/12/31.
//  Copyright © 2015年 孙智慧. All rights reserved.
//

#import "MusicPlayController.h"
#import "PayOrderSetupOne.h"
#import "XCHudHelper.h"

#define kRandomColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

#define font [UIFont systemFontOfSize:15]

//单例模式对象
MusicPlayController *musicPlay=nil;

NSString *const kTBPlayerStateChangedNotification    = @"TBPlayerStateChangedNotification";

@implementation MusicPlayController

-(void) opSuccessForDownLoad:(id)data andFlag:(NSString *)flag
{
    
}

-(void) opSuccessForPost:(id)data
{
    operation=nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *data1 = [dataStr objectFromJSONString];
    
    NSString *v=[data1 objectForKey:@"result"];
    
    if([v isEqualToString:@"1"])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.txtCommentText setText:@""];
        });
    }
    
}
-(void) opFail:(NSString *)errorMessage
{
    
}

#pragma mark 单例模式
+(MusicPlayController *)sharedMyClass
{
    @synchronized(self)
    {
        //为了确保多线程情况下，仍然确保实体的唯一性
        if (!musicPlay)
        {
            musicPlay= [[self alloc] init]; //该方法会调用 allocWithZone
        }
        
    }
    
    return musicPlay;
    
}

+(id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (!musicPlay)
        {
            musicPlay = [super allocWithZone:zone]; //确保使用同一块内存地址
            return musicPlay;
        }
    }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone;
{
    
    return self;
}

#pragma mark 初始化弹幕对象
- (void)setupDanmakuView
{
    CGRect rect =  CGRectMake(0, 2, CGRectGetWidth(self.viewmaku.bounds), CGRectGetHeight(self.viewmaku.bounds)-50);
    _danmakuView = [[CFDanmakuView alloc] initWithFrame:rect];
    // _danmakuView.backgroundColor=[UIColor redColor];
    _danmakuView.duration = 6.5;
    _danmakuView.centerDuration = 2.5;
    _danmakuView.lineHeight = 25;
    _danmakuView.maxShowLineCount = 15;
    _danmakuView.maxCenterLineCount = 5;
    _danmakuView.delegate = self;
    [self.viewmaku addSubview:_danmakuView];
}

-(void) loadComment
{
    operation = [[LoginOperation alloc] initWithDelegate:self];
    
    NSString *URL= [FxGlobal getServiceUrl:@"Comment" andFuncName:@"CommentList"];
    
    NSDictionary * dictInfo = @{@"url":[NSString stringWithFormat:@"%@?musicID=%@",URL,[ZYMusicTool playingMusic].musicID]};
    
    [operation setOpInfo:dictInfo];
    
    [operation get:5];
}



#pragma mark 初始化弹幕数据
- (void)setupDanmakuData
{
    [_danmakuView clear];
    
    [self loadComment];
    
    
}

- (NSTimeInterval)danmakuViewGetPlayTime:(CFDanmakuView *)danmakuView
{
    if(self.videoSlider.value == self.videoSlider.maximumValue)
        [_danmakuView stop];
    return self.videoSlider.value;
}

- (BOOL)danmakuViewIsBuffering:(CFDanmakuView *)danmakuView
{
    return NO;
}

//底部弹出层 1
- (IBAction)openEq:(UIButton *)sender
{
    if(sender.tag==0)
    {
        self.viewSendMaku.hidden=NO;
        
        sender.tag=1;
        
        [_danmakuView start];
    }
    else
    {
        self.viewSendMaku.hidden=YES;
        
        sender.tag=0;
        
        [_danmakuView stop];
        
    }
    
}

- (IBAction)btnSendMaku:(id)sender {
    
    if([self.txtCommentText.text isEqualToString:@""])
    {
        [UIView showAlertView:@"提示" andMessage:@"要发送的内容不能为空" andHost:self];
    }
    else
    {
        [self.txtCommentText resignFirstResponder];
        
        int time = ([self danmakuViewGetPlayTime:nil]+1);
        
        NSString *mString = self.txtCommentText.text;
        
        [self myTask:time];
        
        CFDanmaku* danmaku = [[CFDanmaku alloc] init];
        
        danmaku.contentStr = [[NSMutableAttributedString alloc] initWithString:mString attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15], NSForegroundColorAttributeName : kRandomColor}];
        
        danmaku.timePoint = time;
        
        [_danmakuView sendDanmakuSource:danmaku];
    }
    
}

- (void)myTask:(int) time
{
    
    operation= [[LoginOperation alloc] initWithDelegate:self];
    
    //开始保存数据
    
    NSString *djID= [Common getUserDefaults:@"djID"];
    
    NSString *MusicID= [self playingMusic].musicID;
    
    NSString *CommentText = self.txtCommentText.text;
    
    NSString *MusicTime= [NSString stringWithFormat:@"%d",time*1000];
    
    NSString *url= [FxGlobal getServiceUrl:@"Comment" andFuncName:@"SaveComment"];
    
    NSString *md5Str= [NSString stringWithFormat: @"CommentText=%@&djID=%@&MusicID=%@&MusicTime=%@&key=tqa",CommentText,djID,MusicID,MusicTime];
    
    NSString *sign = [Common createMD5:md5Str];
    
    NSString *body=[NSString stringWithFormat:@"{\"CommentText\":\"%@\",\"djID\":\"%@\",\"MusicID\":\"%@\",\"MusicTime\":\"%@\",\"sign\":\"%@\",\"clicentid\":\"1\"}",CommentText,djID,MusicID,MusicTime,sign];
    
    NSDictionary *dictInfo = @{@"url":url,@"body":body};
    
    [operation setOpInfo:dictInfo];
    
    [operation post];
    
}

- (void)actionShareSheet:(HJCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 1:
            [self doShareSession];
            break;
        case 2:
            [self doShareTimeline];
            break;
            
    }
}

// 底部弹出层 3.实现代理方法，需要遵守HJCActionSheetDelegate代理协议
- (void)actionSheet:(HJCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
    }
}

//暂停滚动
- (void) pasumeRoation:(UIView *) _view
{
    CFTimeInterval pasueTime=  [_view.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    
    _view.layer.speed = 0.0;
    
    _view.layer.timeOffset= pasueTime;
}

-(void) stopNavRightBtnRoation
{
    UIBarButtonItem *item =  self.navigationItem.rightBarButtonItem;
    
    UIButton *btn= (UIButton *) item.customView;
    
    [self pasumeRoation:btn];
}

//设置自定义按钮
- (UIButton *)customButton:(NSString *)imageName selector:(SEL)sel
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    btn.frame = CGRectMake(0, 0, 22, 22);
    
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    
    [btn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
}

//设置右侧按钮
- (void)setNavigationRight:(NSString *)imageName sel:(SEL)sel
{
    
    UIButton *btn=[self customButton:imageName selector:sel];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.rightBarButtonItem = item;
    
}
//设置导航栏按钮
-(void) setBackBarButton
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    
    self.navigationItem.backBarButtonItem = item;
}
//设置导航栏中心图
- (void)setNavigationTitleImage:(NSString *)imageName
{
    UIImage *image = [UIImage imageNamed:imageName];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    
    imageView.contentMode= UIViewContentModeScaleAspectFit;
    
    self.navigationItem.titleView = imageView;
}

-(void)initControl
{
    self.btnTm.enabled=NO;
    
    self.viewSendMaku.hidden=YES;
    
    self.btnNext.enabled=NO;
    
    self.btnPrv.enabled = NO;
    
    self.txtCommentText.delegate=self;
    
    self.txtCommentText.keyboardType= UIKeyboardTypeURL;
    
    self.txtCommentText.returnKeyType= UIReturnKeyDone;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initControl];
    
    _isPauseByUser= NO;
    
    isLocal=NO;
    
    isChangeQuality=NO;
    
    //歌曲循环模式
    loop = 1; // 0 单曲循环 1 列表播放 2 交叉循环
    
    self.imgHead.layer.cornerRadius=32;
    
    self.imgHead.clipsToBounds=YES;
    
    //设置唱针
    self.imgViewChangZhen.layer.anchorPoint=CGPointMake(0.60, 0.20);
    
    self.imgViewChangZhen.transform= CGAffineTransformMakeRotation(-M_PI/10);
    
    (oldTransform)= self.imgViewChangZhen.transform;
    
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    
    [Common setCover:self.bgImgView];
    
    [self setupDanmakuView];
    
    [self customVideoSlider];
    
    //将要进入后台
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; // 让后台可以处理多媒体的事件
    
    [self becomeFirstResponder];
    
    [self displayImg];
}

-(void)viewDidDisappear:(BOOL)animated
{
    //End recieving events
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (IBAction)onClick:(UIButton *)sender
{
    [self playOrPause];
}

-(void) playOrPause
{
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        
        if(_isRoationing)
        {
            [self pasue];
        }
        else
        {
            [self play];
        }
    } completion:^(BOOL finished) {
        
    }];
}

-(void) pasue
{
    
    [self.player pause];
    
    [self.coverImgView pasumeRoation];
    
    _isRoationing=NO;
    
    self.imgViewChangZhen.transform=(oldTransform);// CGAffineTransformMakeRotation(-M_PI/10);
    
    [self.btnPlay setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    
    _isPauseByUser= YES;
}

-(void) play
{
    if (isInited)
    {
        [self.player play];
        
        [self.coverImgView resmeRoation];
        
        _isRoationing= YES;
        
        self.imgViewChangZhen.transform= CGAffineTransformMakeRotation(M_PI/20);
        
        [self.btnPlay setImage:[UIImage imageNamed:@"pasue"] forState:UIControlStateNormal];
        
        _isPauseByUser= NO;
    }
}

#pragma mark 初始化音乐的品质 根据会员的等级可以播放的品质 控制显示
-(NSString *) displayQuality
{
    
    isLocal=NO;
    
    if(qualityArray == nil)
    {
        qualityArray= [[NSMutableArray alloc]init];
    }
    
    [qualityArray removeAllObjects];
    
    //文件地址
    NSString *filepath;
    //规格ID
    NSInteger qualityID = 0;
    //规格名称
    NSString *qualityName;
    
    NSArray *array= [ZYMusicTool playingMusic].musicListArray;
    
    NSString *musicID= [ZYMusicTool playingMusic].musicID;
    
    for (NSInteger i=0; i<array.count; i++)
    {
        
        NSDictionary *dict =  [array objectAtIndex:i];
        
        if([[dict objectForKey:@"Priority"] isEqualToString:@"1"])
        {
            filepath=[dict objectForKey:@"FilePath"];
            qualityName=[dict objectForKey:@"QualityName"];
            qualityID=[[dict objectForKey:@"QualityID"] intValue];
        }
        
        if([[dict objectForKey:@"CanPlay"] isEqualToString:@"1"])
        {
            [qualityArray addObject:dict];
        }
    }
    
    NSString *result=[Common checkMusicIsExists:musicID qualityID:@"2"];
    
    if(![result isEqualToString:@""])
    {
        filepath=result;
        
        qualityName=@"320";
        
        qualityID=2;
        
        isLocal=YES;
    }
    else
    {
//        result=[Common checkCacheMusciIsExists:musicID qualityID:@"2"];
//        
//        if (![result isEqualToString:@""])
//        {
//            filepath=result;
//            
//            qualityName=@"128";
//            
//            qualityID=2;
//            
//            isLocal=YES;
//        }
//        else
//        {
            result=[Common checkCacheMusciIsExists:musicID qualityID:@"1"];
            
            if (![result isEqualToString:@""])
            {
                filepath=result;
                
                qualityName=@"128";
                
                qualityID=1;
                
                isLocal=YES;
            }
//        }
    }
    
    [self.btnQuality setTitle:qualityName forState:UIControlStateNormal];
    
    self.btnQuality.tag=qualityID;
    
    return filepath;
    
}


#pragma mark 播放完事件
- (void)musicPlayDidEnd:(NSNotification *)notification
{
    NSLog(@"Play end");
    
    __weak typeof(self) weakSelf = self;
    
    [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        
        [weakSelf.videoSlider setValue:0.0 animated:YES];
        
        // 通知其他页面关闭
        SendNotify(NofifyMusicPlay, nil);
        
        [weakSelf stopNavRightBtnRoation]; //关闭本页面转动
        
        [weakSelf.coverImgView pasumeRoation];
        
        _isRoationing=NO;
        
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear
                         animations:^{weakSelf.imgViewChangZhen.transform= oldTransform;}
                         completion:^(BOOL finished){}];
        
        [weakSelf.btnPlay setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        
        if(loop==0)// 单曲循环
        {
            [self playOrPause];
        }
        else if(loop ==1 ) //列表循环
        {
            if([self.playMode isEqualToString:@"one"])
            {
                [self onClick:self.btnPlay];
            }
            else
            {
                [self nextMusic];
                
                [self playOrPause];
            }
        }
        else if(loop == 2) //随机播放
        {
            if([self.playMode isEqualToString:@"one"])
            {
                [self onClick:self.btnPlay];
            }
            else
            {
                
                NSInteger value = arc4random() % [[ZYMusicTool musics] count];
                
                ZYMusic *music=   [[ZYMusicTool musics]objectAtIndex:value];
                
                [ZYMusicTool setPlayingMusic:music];
                
                NSString *filepath = [self displayQuality];
                
                [self displayImg];
                
                [self initMusic:filepath];
                
                [self playOrPause];;
                
            }
        }
        
    }];
}

-(void) startPlay
{
    
    [self.player play];
    
    if(self.playingMusic==nil)
    {
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             self.imgViewChangZhen.transform= CGAffineTransformMakeRotation(M_PI/20);
                         }
                         completion:^(BOOL finished){}];
        
        //唱盘开始旋转
        [self.coverImgView startRoating];
    }
    else
    {
        if(_isRoationing == NO)
        {
            [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear
                             animations:^{
                                 self.imgViewChangZhen.transform= CGAffineTransformMakeRotation(M_PI/20);
                             }
                             completion:^(BOOL finished){}];
            
            //唱盘开始旋转
            [self.coverImgView resmeRoation];
        }
        
    }
    
    self.playingMusic =[ZYMusicTool playingMusic];
    
    _isRoationing=YES;
    
    [self.btnPlay setImage:[UIImage imageNamed:@"pasue"] forState:UIControlStateNormal];
    
    isInited=YES;
    
    [Common stopActivityView:self.videoSlider];
}

- (NSDateFormatter *)dateFormatter
{
    if (!_dateFormatter)
    {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}

- (NSString *)convertTime:(CGFloat)second
{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    
    if (second/3600 >= 1)
    {
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    }
    else
    {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [[self dateFormatter] stringFromDate:d];
    
    return showtimeNew;
}

//计算缓冲进度
- (NSTimeInterval)availableDuration
{
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    
    // 获取缓冲区域
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    
    // 计算缓冲总进度
    NSTimeInterval result = startSeconds + durationSeconds;
    
    return result;
}

#pragma mark 播放事件
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"])
    {
        if ([playerItem status] == AVPlayerStatusReadyToPlay && _isPauseByUser== NO)
        {
            self.btnPlay.enabled = YES;
            
            CMTime duration = self.playerItem.duration;// 获取视频总长度
            
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
            
            _totalTime = [self convertTime:totalSecond];// 转换成播放时间
            
            _lblTotltSec.text=_totalTime;
            
            _lblCurrSec.text=@"00:00";
            
            self.videoSlider.maximumValue = CMTimeGetSeconds(duration);
            
            
            if(!isAddTime)
            {
                [self monitoringPlayback:self.playerItem];
            }
            
            [self startPlay];
            
            if([_playMode isEqualToString:@"more"])
            {
                self.btnPrv.enabled=YES;
                
                self.btnNext.enabled= YES;
            }
        }
        else if ([playerItem status] == AVPlayerStatusFailed)
        {
            NSLog(@"AVPlayerStatusFailed");
        }
    }
    else if ([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        NSLog(@"Time Interval:%f",timeInterval);
        CMTime duration = _playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
    }
    
    else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) { //监听播放器在缓冲数据的状态
        
        if (playerItem.isPlaybackBufferEmpty) {
            self.state = TBPlayerStateBuffering;
            [self bufferingSomeSecond];
        }
    }
}

- (void)bufferingSomeSecond
{
    // playbackBufferEmpty会反复进入，因此在bufferingOneSecond延时播放执行完之前再调用bufferingSomeSecond都忽略
    static BOOL isBuffering = NO;
    
    if (isBuffering)
    {
        return;
    }
    
    isBuffering = YES;
    
    // 需要先暂停一小会之后再播放，否则网络状况不好的时候时间在走，声音播放不出来
    [self.player pause];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 如果此时用户已经暂停了，则不再需要开启播放了
        if (self.isPauseByUser)
        {
            isBuffering = NO;
            
            return;
        }
        
        [self.player play];
        
        // 如果执行了play还是没有播放则说明还没有缓存好，则再次缓存一段时间
        
        isBuffering = NO;
        
        if (!self.playerItem.isPlaybackLikelyToKeepUp)
        {
            [self bufferingSomeSecond];
        }
    });
}


// 自定义UISlider外观
- (void)customVideoSlider
{
    
    
    UIImage *tumbImage= [UIImage imageNamed:@"slidebutton.png"];
    
    [self.videoSlider setThumbImage:tumbImage forState:UIControlStateNormal];
    
    //注意这里要加UIControlStateHightlighted的状态，否则当拖动滑块时滑块将变成原生的控件
    [self.videoSlider setThumbImage:tumbImage forState:UIControlStateHighlighted];
    
    [self.videoSlider setThumbImage:tumbImage forState:UIControlStateNormal];
    
    UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
    
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    //[self.videoSlider setMinimumTrackImage:transparentImage forState:UIControlStateNormal];
    
    [self.videoSlider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
}

// 监听播放状态
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    
    __weak typeof(self) weakSelf = self;
    
    isAddTime=YES;
    
    CMTime cmTime=  CMTimeMake(1, 1);
    
    self.playbackTimeObserver = [self.player addPeriodicTimeObserverForInterval:cmTime queue:NULL usingBlock:^(CMTime time)
                                 {
                                     CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
                                     
                                     [weakSelf.videoSlider setValue:currentSecond animated:YES];
                                     
                                     weakSelf.lblCurrSec.text=[weakSelf convertTime:currentSecond];
                                     
                                 }];
}

- (IBAction)videoSlierChangeValue:(id)sender
{
    UISlider *slider = (UISlider *)sender;
    NSLog(@"value change:%f",slider.value);
    
    if (slider.value == 0.000000) {
        __weak typeof(self) weakSelf = self;
        [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
            [weakSelf.player play];
            
            if(!_isRoationing)
            {
                
                [weakSelf.coverImgView resmeRoation];
                
                _isRoationing= YES;
                
                [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
                    weakSelf.imgViewChangZhen.transform= CGAffineTransformMakeRotation(M_PI/20);
                    
                } completion:^(BOOL finished) {
                    
                }];
                
                [weakSelf.btnPlay setImage:[UIImage imageNamed:@"pasue"] forState:UIControlStateNormal];
            }
            
        }];
    }
}

- (IBAction)videoSlierChangeValueEnd:(id)sender {
    UISlider *slider = (UISlider *)sender;
    NSLog(@"value end:%f",slider.value);
    CMTime changedTime = CMTimeMakeWithSeconds(slider.value, 1);
    
    __weak typeof(self) weakSelf = self;
    [self.player seekToTime:changedTime completionHandler:^(BOOL finished) {
        [weakSelf.player play];
        if(!_isRoationing)
        {
            
            [weakSelf.coverImgView resmeRoation];
            
            _isRoationing= YES;
            
            [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
                weakSelf.imgViewChangZhen.transform= CGAffineTransformMakeRotation(M_PI/20);
                
            } completion:^(BOOL finished) {
                
            }];
            
            [weakSelf.btnPlay setImage:[UIImage imageNamed:@"pasue"] forState:UIControlStateNormal];
        }
        
    }];
}

- (IBAction)btnNextMusic:(UIButton *)sender
{
    [self nextMusic];
    
}

-(void) nextMusic
{
    if([_playMode isEqualToString:@"more"])
    {
        self.btnPrv.enabled=NO;
        
        self.btnNext.enabled= NO;
    }
    
    ZYMusic *music= [ZYMusicTool nextMusic];
    
    [ZYMusicTool setPlayingMusic:music];
    
    NSString *filepath = [self displayQuality];
    
    [self displayImg];
    
    [self initMusic:filepath];
}

-(void) preMusic
{
    if([_playMode isEqualToString:@"more"])
    {
        self.btnPrv.enabled=NO;
        
        self.btnNext.enabled= NO;
    }
    
    ZYMusic *music= [ZYMusicTool previousMusic];
    
    [ZYMusicTool setPlayingMusic:music];
    
    NSString *filepath = [self displayQuality];
    
    [self displayImg];
    
    [self initMusic:filepath];
}

- (IBAction)btnPreMusic:(UIButton *)sender
{
    
    [self preMusic];
}

- (IBAction)backBtnClick:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)sss
{
    if(self.btnTm.tag==1)
    {
        [_danmakuView refresh];
    }
    
    if (self.playingMusic != [ZYMusicTool playingMusic])
    {
        NSString *filepath = [self displayQuality];
        
        [self initMusic:filepath];
    }
}

#pragma mark 调解声音大小
-(void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.playingMusic != [ZYMusicTool playingMusic])
    {
        [self loadData:[ZYMusicTool playingMusic].djID];
    }
    
    state= [Common checkNetworkState];
    
    if([state isEqualToString: @"2"]) //4G
    {
        [UIView showAlertView:@"网络连接提醒" andMessage:@"当前网络无Wi-Fi，继续在线试听可能会被运营商收取流量费用" andHost:self sel:^(UIAlertAction *action) {
            [self sss];
        }];
    }
    else if([state isEqualToString:@"0"]) //无网络
    {
        [UIView showAlertView:@"网络连接提醒" andMessage:@"当前网络无Wi-Fi或手机网络，不能继续在线播放" andHost:self];
    }
    else
    {
        if(self.btnTm.tag==1)
        {
            [_danmakuView refresh];
        }
        
        if (self.playingMusic != [ZYMusicTool playingMusic])
        {
            NSString *filepath = [self displayQuality];
            
            [self initMusic:filepath];
        }
    }
}

-(void) dealloc
{
    
    [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
    
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    
    [self.player removeTimeObserver:self.playbackTimeObserver];
    
}

#pragma mark 加载用户信息
-(void) loadData:(NSString *)djID
{
    operation= [[LoginOperation alloc] initWithDelegate:self];
    
    NSString *url= [FxGlobal getServiceUrl:@"User" andFuncName:@"FansCount"];
    
    NSString *u= [NSString stringWithFormat:@"%@?p_djID=%@", url,djID];
    
    NSDictionary *dictInfo = @{@"url":u};
    
    [operation setOpInfo:dictInfo];
    
    [operation get:0];
    
    operation= [[LoginOperation alloc] initWithDelegate:self];
    
    NSString *url1= [FxGlobal getServiceUrl:@"User" andFuncName:@"MusicCount"];
    
    NSString *u1= [NSString stringWithFormat:@"%@?p_djID=%@", url1,djID];
    
    NSDictionary *dictInfo1 = @{@"url":u1};
    
    [operation setOpInfo:dictInfo1];
    
    [operation get:1];
    
    operation= [[LoginOperation alloc] initWithDelegate:self];
    
    NSString *url2= [FxGlobal getServiceUrl:@"User" andFuncName:@"FocusCount"];
    
    NSString *u2= [NSString stringWithFormat:@"%@?p_djID=%@",url2,djID];
    
    NSDictionary *dictInfo2 = @{@"url":u2};
    
    [operation setOpInfo:dictInfo2];
    
    [operation get:2];
    
    operation= [[LoginOperation alloc] initWithDelegate:self];
    
    NSString *url3= [FxGlobal getServiceUrl:@"User" andFuncName:@"DJInfo"];
    
    NSString *subDJID= [Common getUserDefaults:@"djID"];
    
    NSString *u3= [NSString stringWithFormat:@"%@?p_djID=%@&subDJID=%@", url3,djID,subDJID];
    
    NSDictionary *dictInfo3 = @{@"url":u3};
    
    [operation setOpInfo:dictInfo3];
    
    [operation get:3];
    
}

-(void) DownLoadRequest:(NSString *)djID andMusicID:(NSString *)musicID andQualityID:(NSString *)qualityID
{
    operation= [[LoginOperation alloc] initWithDelegate:self];
    
    NSString *url= [FxGlobal getServiceUrl:@"Music" andFuncName:@"DownLoadRequest"];
    
    NSString *finallUrl= [NSString stringWithFormat:@"%@?djID=%@&musicID=%@&qualityID=%@", url,djID ,musicID,qualityID];
    
    NSDictionary *dictInfo = @{@"url":finallUrl};
    
    [operation setOpInfo:dictInfo];
    
    [operation get:4];
    
}



-(void)opSuccessForGet:(id)data andFlag:(NSInteger)getflag
{
    operation=nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *data1 = [dataStr objectFromJSONString];
    
    if (getflag  ==0) {
        NSString *v=[data1 objectForKey:@"count"];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.lblFansCount.text=v;
        });
        
    }
    else if (getflag==1) {
        NSString *v=[data1 objectForKey:@"count"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.lblMusicCount.text=v;
        });
    }
    else if (getflag==2) {
        NSString *v=[data1 objectForKey:@"count"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.lblFocusCount.text=v;
        });
    }
    else  if(getflag==3)
    {
        NSString *Code=[data1 objectForKey:@"Code"];
        
        NSString *NickName=[data1 objectForKey:@"NickName"];
        
        NSString *HeadImg=[data1 objectForKey:@"HeadImg"];
        
        NSString *HeadImgName=[data1 objectForKey:@"HeadImgName"];
        
        NSString *issub= [data1 objectForKey:@"issub"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.lbldjCode setText:Code];
            
            [self.lblNickName setText:NickName];
            
            if([issub isEqualToString:@"1"])
            {
                self.btnLike.tag=1;
                
                [self.btnLike setImage:[UIImage imageNamed:@"like2"] forState:UIControlStateNormal];
            }
            else
            {
                self.btnLike.tag=0;
                
                [self.btnLike setImage:[UIImage imageNamed:@"like1"] forState:UIControlStateNormal];
            }
        });
        
        [Common downLoadImageByURL:self.imgHead andURL:HeadImg andName:HeadImgName];
        
    }
    
    else if(getflag==5)
    {
        NSArray *danmakusDicts= [data1 objectForKey:@"data"];
        
        NSMutableArray* danmakus = [NSMutableArray array];
        
        for (NSDictionary* dict in danmakusDicts)
        {
            CFDanmaku* danmaku = [[CFDanmaku alloc] init];
            
            NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc] initWithString:dict[@"CommentText"] attributes:@{NSFontAttributeName : font, NSForegroundColorAttributeName : kRandomColor}];
            
            danmaku.contentStr = contentStr;
            
            NSString * MusicTime = dict[@"MusicTime"];
            
            danmaku.timePoint = [MusicTime doubleValue] / 1000;
            
            danmaku.position = 0;
            
            [danmakus addObject:danmaku];
            
        }
        
        [_danmakuView prepareDanmakus:danmakus];
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            self.btnTm.enabled=YES;
            
            if(self.btnTm.tag==1)
            {
                [_danmakuView start];
            }
            
        });
        
    }
    else if(getflag == 4)
    {
        NSString *resut=[data1 objectForKey:@"result"];
        
        if([resut isEqualToString:@"1"])
        {
            DownLoadObjects *dlos=[DownLoadObjects sharedMyClass];
            
            [dlos initArray];
            
            NSString *filePath=[downloadQuality objectForKey:@"FilePath"];
            
            NSString *qualityID= [downloadQuality objectForKey:@"QualityID"];
            
            NSString *storePath=  [NSString stringWithFormat:@"%@/%@_%@.%@",[FxGlobal getDownLoad],self.playingMusic.musicID,qualityID,@"mp3"];
            
            DownLoad *dl=[[DownLoad alloc] init:filePath andStorePath:storePath];
            
            [dl setDeleteDel:dlos];
            
            dl->zyMusic= self.playingMusic;
            
            [dl ddLoad];
            
            [dlos.downLoadTask addObject:dl];
        }
        else if([resut isEqualToString:@"3000001"])
        {
            [UIView showAlertView:@"提示" andMessage:@"您的积分不足，请充值" andHost:self sel:^(UIAlertAction *action)
            {
                
//                PayOrderSetupOne *poso= [self.storyboard instantiateViewControllerWithIdentifier:@"PayOrderSetupOne"];
                
                PayOrderSetupOne *poso= [[PayOrderSetupOne alloc]init];

                
                [self presentViewController:poso animated:true completion:nil];
            }];
        }
        
    }
}
#pragma mark 文本框键盘位置控制事件

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    const int movementDistance = 220; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    
    int movement = (up ? -movementDistance : movementDistance);
    
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    [self btnSendMaku:nil];
    
    return YES;
}

- (IBAction)btnMusicList:(id)sender
{
    flag=1;
    
    sheet = [[HJCActionSheet alloc] initWithDelegateAndArray:self CancelTitle:@"关闭" pageTitle:@"播放列表" andFlag:flag];
    
    [sheet show];
}


#pragma mark 设置表格有几个数据区域
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark 设置表格的行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

#pragma mark 设置表格有几行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(flag==1)
    {
        if([_playMode isEqualToString:@"more"])
        {
            return [[ZYMusicTool musics] count];
        }
        else
        {
            return 1;
        }
    }
    else if(flag ==2)
    {
        return self.playingMusic.musicListArray.count;
    }
    else
    {
        return qualityArray.count;
    }
}

#pragma mark 表格绑定数据
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * const kCellIdentifier = @"tvcmusiclist";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier];
    }
    cell.backgroundColor=[UIColor clearColor];
    
    if (flag==1)
    {
        
        UIImageView *imgView=[[UIImageView alloc]init];
        
        imgView.frame= CGRectMake(0.0f, 0.0f, 20.0f, 20.0f);
        
        imgView.image=[UIImage imageNamed:@"del"];
        
        cell.accessoryView=imgView;
        
        cell.textLabel.textColor=[UIColor whiteColor];
        
        if([_playMode isEqualToString:@"more"])
        {
            ZYMusic *zyMusic=  [[ZYMusicTool musics] objectAtIndex:indexPath.row];
            
            if([self.playingMusic.name isEqualToString:zyMusic.name])
            {
                
                UIImageView * biv = [[UIImageView alloc]init];
                
                CGRect  fbiv = CGRectMake(15, 13, 20, 20);
                
                biv.frame = fbiv;
                
                UIImage *img=[UIImage imageNamed:@"horn"];
                
                [biv setImage:img];
                
                [cell addSubview:biv];
                
                UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(45, 10, 240, 25)];
                
                label.clipsToBounds=YES;
                
                [label setText: zyMusic.name];
                
                label.textColor=[UIColor redColor];
                
                [cell addSubview:label];
                
            }
            else
            {
                cell.textLabel.text= zyMusic.name;
            }
            
        }
        else
        {
            
            UIImageView * biv = [[UIImageView alloc]init];
            
            CGRect  fbiv = CGRectMake(15, 13, 20, 20);
            
            biv.frame = fbiv;
            
            UIImage *img=[UIImage imageNamed:@"horn"];
            
            [biv setImage:img];
            
            [cell addSubview:biv];
            
            UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(45, 10, 240, 25)];
            
            label.clipsToBounds=YES;
            
            [label setText: self.playingMusic.name];
            
            label.textColor=[UIColor redColor];
            
            [cell addSubview:label];
            
            
        }
    }
    else if(flag==2)
    {
        
        NSDictionary *dict = [[ZYMusicTool playingMusic].musicListArray objectAtIndex:indexPath.row];
        
        NSString *qualitySize= [dict objectForKey:@"Size"];
        
        cell.textLabel.text= [NSString stringWithFormat:@"%@ (%@)", [dict objectForKey:@"QualityName"], [Common convertSize: [qualitySize floatValue]]];
        
        cell.textLabel.textColor=[UIColor whiteColor];
        
        cell.textLabel.tag = [[dict objectForKey:@"Point"] intValue];
        
        
    }
    else if(flag == 3)
    {
        
        NSDictionary *dict = [qualityArray objectAtIndex:indexPath.row];
        
        cell.textLabel.text= [NSString stringWithFormat:@"%@", [dict objectForKey:@"QualityName"]];
        
        cell.textLabel.textColor=[UIColor whiteColor];
        
        if([[dict objectForKey:@"QualityID"] intValue] == self.btnQuality.tag)
        {
            
            cell.textLabel.textColor=[UIColor redColor];
            
            UIImageView *imgView=[[UIImageView alloc]init];
            
            imgView.frame= CGRectMake(0.0f, 0.0f, 20.0f, 20.0f);
            
            imgView.image=[UIImage imageNamed:@"selected"];
            
            cell.accessoryView=imgView;
        }
        
    }
    
    return cell;
    
}
- (IBAction)btnDownLoadClick:(id)sender
{
    flag=2;
    
    sheet = [[HJCActionSheet alloc] initWithDelegateAndArray:self CancelTitle:@"关闭" pageTitle:@"下载列表" andFlag:flag];
    
    [sheet show];
}





#pragma mark 歌曲列表点击事件
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(flag==1) //列表
    {
        ZYMusic *selectMusic= [[ZYMusicTool musics] objectAtIndex:indexPath.row];
        
        [ZYMusicTool setPlayingMusic:selectMusic];
        
        NSString *filepath = [self displayQuality];
        
        [self displayImg];
        
        [self initMusic:filepath];
        
        [self.player play];
        
        if(!_isRoationing)
        {
            [self.coverImgView resmeRoation];
            
            _isRoationing= YES;
            
            self.imgViewChangZhen.transform= CGAffineTransformMakeRotation(M_PI/20);
            
            [self.btnPlay setImage:[UIImage imageNamed:@"pasue"] forState:UIControlStateNormal];
        }
        
    }
    else if(flag==2)// 下载
    {
        UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        cell.textLabel.textColor=[UIColor redColor];
        
        UIImageView *imgView=[[UIImageView alloc]init];
        
        imgView.frame= CGRectMake(0.0f, 0.0f, 20.0f, 20.0f);
        
        imgView.image=[UIImage imageNamed:@"selected"];
        
        cell.accessoryView=imgView;
        
        downloadQuality = [self.playingMusic.musicListArray objectAtIndex:indexPath.row];
        
        NSString *qualityID= [downloadQuality objectForKey:@"QualityID"];
        
        NSString *storePath= [NSString stringWithFormat:@"%@/%@_%@.%@",[FxGlobal getDownLoad],self.playingMusic.musicID,qualityID,@"mp3"];
 
        if(![FxFileUtility isFileExist:storePath]) //文件不存在 检查是否下载过
        {
            [self DownLoadRequest:[Common getUserDefaults:@"djID"] andMusicID:self.playingMusic.musicID andQualityID:qualityID];
        }
        else
        {
            [XCHudHelper showMessage:@"歌曲已经下载"];
        }
    }
    else if(flag==3)//切换品质
    {
        
        NSDictionary *dict=  [qualityArray objectAtIndex:indexPath.row];
        
        [self.btnQuality setTitle:[dict objectForKey:@"QualityName"] forState:UIControlStateNormal];
        
        NSString *qualityID=[dict objectForKey:@"QualityID"];
        
        NSString *musicID= self.playingMusic.musicID;
        
        self.btnQuality.tag= [qualityID intValue];
        
        NSString *filePath = [dict objectForKey:@"FilePath"];
        
        isLocal= NO;
        
        isChangeQuality= YES;
        
        NSString  *result=@"";
        
        if([qualityID isEqualToString:@"3"])
        {
            result= [Common checkMusicIsExists:musicID qualityID:qualityID];
        }
        else
        {
            result= [Common checkCacheMusciIsExists:musicID qualityID:qualityID];
        }
        
        
        if (![result isEqualToString:@""])
        {
            filePath=result;
            
            isLocal= YES;
            
        }
        
        [self displayImg];
        
        [self initMusic:filePath];
    }
    
    [sheet coverClick];
    
}

- (IBAction)btnLoop:(id)sender
{
    if(loop == 0 )
    {
        loop =1;
        [self.btnLoop setImage:[UIImage imageNamed:@"loop" ] forState:UIControlStateNormal];
        [XCHudHelper showMessage:@"顺序播放"];
    }
    else if(loop == 1)
    {
        loop =2 ;
        [self.btnLoop setImage:[UIImage imageNamed:@"loopx" ] forState:UIControlStateNormal];
        [XCHudHelper showMessage:@"随机播放"];
    }
    else if(loop ==2)
    {
        loop =0 ;
        [self.btnLoop setImage:[UIImage imageNamed:@"loop1" ] forState:UIControlStateNormal];
        [XCHudHelper showMessage:@"单曲循环"];
        
    }
}

- (IBAction)btnShareClick:(id)sender
{
    sheet = [[HJCActionSheet alloc] initWithDelegateForShare:self CancelTitle:@"关闭"];
    
    [sheet show];
    
}

#pragma mark 分享到微信
- (void)doShareSession
{
    WXMediaMessage *message = [WXMediaMessage message];
    
    message.title = @"混吧";
    
    message.description = [self playingMusic].name;
    
    [message setThumbImage:[UIImage imageNamed:@"res2.png"]];
    
    WXWebpageObject *ext = [WXWebpageObject object];
    
    ext.webpageUrl = [self playingMusic].shareURL;
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    
    req.message = message;
    
    req.bText = NO;
    
    req.scene = WXSceneSession;
    
    if (![WXApi sendReq:req]) {
        
        [UIView showAlertView:@"提示" andMessage:@"未安装微信" andHost:self];
    }
}

#pragma mark 分享到微信朋友圈
- (void)doShareTimeline
{
    WXMediaMessage *message = [WXMediaMessage message];
    
    message.title = @"";
    
    message.description = [self playingMusic].name;
    
    [message setThumbImage:[UIImage imageNamed:@"res2.png"]];
    
    WXWebpageObject *ext = [WXWebpageObject object];
    
    ext.webpageUrl = [self playingMusic].shareURL;
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    
    req.message = message;
    
    req.bText = NO;
    
    req.scene = WXSceneTimeline;
    
    if (![WXApi sendReq:req]) {
        
        [UIView showAlertView:@"提示" andMessage:@"未安装微信" andHost:self];
    }
}


- (IBAction)btnLikeClick:(id)sender
{
    UIButton *btn= (UIButton *)sender;
    
    NSString *DJID= [ZYMusicTool playingMusic].djID;
    
    NSString *SubDJID= [Common getUserDefaults:@"djID"];
    
    if(btn.tag == 0 )
    {
        btn.tag=1;
        
        [btn setImage:[UIImage imageNamed:@"like2"] forState:UIControlStateNormal];
        
        if(![DJID isEqualToString:SubDJID])
        {
            operation= [[FansOperation alloc]initWithDelegate:self];
            
            NSString *url= [FxGlobal getServiceUrl:@"user" andFuncName:@"AddFans"];
            
            NSString *md5Str= [NSString stringWithFormat: @"DJID=%@&SubDJID=%@&key=tqa",DJID,SubDJID];
            
            NSString *sign = [Common createMD5:md5Str];
            
            NSString *body=[NSString stringWithFormat:@"{\"DJID\":\"%@\",\"SubDJID\":\"%@\",\"sign\":\"%@\",\"clicentid\":\"1\"}",DJID,SubDJID,sign];
            
            NSDictionary *dictInfo = @{@"url":url,@"body":body};
            
            [operation setOpInfo:dictInfo];
            
            [operation post];
        }
        
    }
    else
    {
        btn.tag=0;
        
        [btn setImage:[UIImage imageNamed:@"like1"] forState:UIControlStateNormal];
        
        if(![DJID isEqualToString:SubDJID])
        {
            operation= [[FansOperation alloc]initWithDelegate:self];
            
            NSString *url= [FxGlobal getServiceUrl:@"user" andFuncName:@"DelFans"];
            
            NSString *md5Str= [NSString stringWithFormat: @"DJID=%@&SubDJID=%@&key=tqa",DJID,SubDJID];
            
            NSString *sign = [Common createMD5:md5Str];
            
            NSString *body=[NSString stringWithFormat:@"{\"DJID\":\"%@\",\"SubDJID\":\"%@\",\"sign\":\"%@\",\"clicentid\":\"1\"}",DJID,SubDJID,sign];
            
            NSDictionary *dictInfo = @{@"url":url,@"body":body};
            
            [operation setOpInfo:dictInfo];
            
            [operation post];
        }
    }
}

-(void) opSuccessForPostEx:(id)data
{
    operation=nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *data1 = [dataStr objectFromJSONString];
    
    NSString *v=[data1 objectForKey:@"result"];
    
    NSLog(@"post结果：%@",v);
    
    if([v isEqualToString:@"1"])
    {
        
    }
    
}
- (IBAction)btnQualityClick:(id)sender
{
    
    flag=3;
    
    sheet = [[HJCActionSheet alloc] initWithDelegateAndArray:self CancelTitle:@"关闭" pageTitle:@"切换品质" andFlag:flag];
    
    [sheet show];
    
}

-(void)configNowPlayingInfoCenter
{
    
    if (NSClassFromString(@"MPNowPlayingInfoCenter"))
    {
        
        NSString *name=[ZYMusicTool playingMusic].name;
        
        NSString *singer= [ZYMusicTool playingMusic].singer;
        
        NSString *album= [ZYMusicTool playingMusic].albumName==nil?@"":[ZYMusicTool playingMusic].albumName;
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        [dict setObject:name forKey:MPMediaItemPropertyTitle];
        
        [dict setObject:singer forKey:MPMediaItemPropertyArtist];
        
        [dict setObject:album forKey:MPMediaItemPropertyAlbumTitle];
        
        NSString *imgName=[ZYMusicTool playingMusic].iconName;
        
        if([Common checkLanchExist:imgName])
        {
            NSString *filePath = [FxGlobal getCacheImage:imgName];
            
            UIImage *img= [UIImage imageWithContentsOfFile:filePath];
            
            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:img];
            
            [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
            
            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
            
        }
        else
        {
            //这里把imageBlock当做了一个变量，它封装了一段代码，这段代码在-(void)AdImg:(NSArray*)arr中
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
                           {
                               NSString *imgPath=[ZYMusicTool playingMusic].icon;
                               
                               NSData * data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgPath]];
                               
                               [data writeToFile:[FxGlobal getCacheImage:imgName] atomically:YES];
                               
                               UIImage * image = [[UIImage alloc] initWithData:data];
                               
                               MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
                               
                               [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
                               
                               [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
                               
                           });
        }
        
        
        
    }
    
}

#pragma mark 清空播放器监听属性
- (void)releasePlayer
{
    if (!self.playerItem)
    {
        return;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.playerItem removeObserver:self forKeyPath:@"status"];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [self.playerItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
    [self.playerItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
    [self.player removeTimeObserver:self.playbackTimeObserver];
    self.playbackTimeObserver = nil;
    self.playerItem = nil;
    
    self.player = nil;
}

#pragma mark 初始化音乐播放
- (void)initMusic:(NSString *)fileUrl
{
    if((self.playingMusic!=[ZYMusicTool playingMusic] && self.playingMusic.name!=[ZYMusicTool playingMusic].name) || isChangeQuality)
    {
        [self.player pause];
        
        _isPauseByUser= NO;
        
        //[self releasePlayer];
        
        NSURL *playUrl=nil;
        
        [self setupDanmakuData];
        
        [Common createActivityView:self.videoSlider];
        
        isInited=NO;
        
        isAddTime=NO;
        
        self.btnPlay.enabled=NO;
        
        //初始化一个播放进度条
        self.videoProgress.progress=0.0;
        
        [self.videoSlider setValue:0.0f animated:true];
        
        if(self.playerItem!=nil)
        {
            [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
            [self releasePlayer];
        }
        
        if(isLocal || IOS_VERSION < 7.0 )
        {
            playUrl = [NSURL fileURLWithPath:fileUrl];
            
            self.musicURLAsset  = [AVURLAsset URLAssetWithURL:playUrl options:nil];
            
            self.playerItem = [AVPlayerItem playerItemWithAsset:_musicURLAsset];
            
            self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
            
        }
        else
        {
            
            NSURL  *tempPlayUrl = [[NSURL alloc] initWithString:[fileUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            
            self.resouerLoader = [[TBloaderURLConnection alloc] init];
            
            self.resouerLoader.musicName= [NSString stringWithFormat:@"%@_%ld",[ZYMusicTool playingMusic].musicID,(long)self.btnQuality.tag];
            
            self.resouerLoader.delegate = self;
            
            playUrl = [_resouerLoader getSchemeVideoURL:tempPlayUrl];
            
            self.musicURLAsset  = [AVURLAsset URLAssetWithURL:playUrl options:nil];
            
            [_musicURLAsset.resourceLoader setDelegate:_resouerLoader queue:dispatch_get_main_queue()];
            
            self.playerItem = [AVPlayerItem playerItemWithAsset:_musicURLAsset];
            
            self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
            
        }
        
        [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
        
        [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
        
        [self.playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
        
        [self.playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
        
        // 本地文件不设置TBPlayerStateBuffering状态
        if ([playUrl.scheme isEqualToString:@"file"]) {
            
            // 如果已经在TBPlayerStatePlaying，则直接发通知，否则设置状态
            if (self.mState == TBPlayerStatePlaying)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:kTBPlayerStateChangedNotification object:nil];
            }
            else
            {
                [self setState:TBPlayerStatePlaying];
            }
        }
        else
        {
            // 如果已经在TBPlayerStateBuffering，则直接发通知，否则设置状态
            if (self.mState == TBPlayerStateBuffering)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:kTBPlayerStateChangedNotification object:nil];
            }
            else
            {
                [self setState: TBPlayerStateBuffering];
            }
            
        }
        
        // 添加视频播放结束通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(musicPlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
    }
}

- (void)setState:(TBPlayerState)mState
{
    if (_mState != TBPlayerStateBuffering) {
        //[[XCHudHelper sharedInstance] hideHud];
    }
    
    if (_mState == mState) {
        return;
    }
    
    _mState = mState;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kTBPlayerStateChangedNotification object:nil];
    
}
#pragma mark - TBloaderURLConnectionDelegate

- (void)didFinishLoadingWithTask:(TBVideoRequestTask *)task
{
    _isFinishLoad = task.isFinishLoad;
}

//网络中断：-1005
//无网络连接：-1009
//请求超时：-1001
//服务器内部错误：-1004
//找不到服务器：-1003
- (void)didFailLoadingWithTask:(TBVideoRequestTask *)task WithError:(NSInteger)errorCode
{
    NSString *str = nil;
    switch (errorCode) {
        case -1001:
            str = @"请求超时";
            break;
        case -1003:
        case -1004:
            str = @"服务器错误";
            break;
        case -1005:
            str = @"网络中断";
            break;
        case -1009:
            str = @"无网络连接";
            break;
            
        default:
            str = [NSString stringWithFormat:@"%@", @"(_errorCode)"];
            break;
    }
    
    [XCHudHelper showMessage:str];
    
}

-(void) displayImg
{
    if (!isChangeQuality)
    {
        [Common downLoadImageByURL:self.bgImgView andURL:[ZYMusicTool playingMusic].icon andName:[ZYMusicTool playingMusic].iconName];
        
        [Common downLoadImageByURL:self.coverImgView.albumImageView andURL:[ZYMusicTool playingMusic].icon andName:[ZYMusicTool playingMusic].iconName];
        
        self.lblMusicName.text= [ZYMusicTool playingMusic].name;
    }
    
    [self configNowPlayingInfoCenter];
    
}

@end
